<?php

namespace App\Models\CacheModel\name_analyze;

use app\common\lib\Util;
use App\Models\Api\BaseCache;
use think\Env;
use traits\model\SoftDelete;
use AstroTool\Cache\CacheManage;

class Zl9NameAnalyzeRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl9_name_analyze_record';

    protected $cacheModel = 'name_analyze.name_analyze_record';

    use SoftDelete;

    /**
     * @param array $data
     * @return int
     */
    public function SaveData(array $data)
    {
        try
        {
            if (isset($data['content']) && is_array($data['content']))
            {
                $data['content'] = json_encode($data['content'], JSON_UNESCAPED_UNICODE);
            }
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['uid'], [$id => $id]);
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * 更新信息
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, array $data)
    {
        try
        {
            if (isset($data['content']) && is_array($data['content']))
            {
                $data['content'] = json_encode($data['content'], JSON_UNESCAPED_UNICODE);
            }
            if (isset($data['share_help_info']) && is_array($data['share_help_info']))
            {
                $data['share_help_info'] = json_encode($data['share_help_info'], JSON_UNESCAPED_UNICODE);
            }
            $this->where(['id' => $id])->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCacheTime(5)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 支付解锁
     * @param int $id
     * @param int $unlockType 解锁方式 2=>微信解锁 3=>支付宝解锁 4=>准币解锁
     * @param string $orderNum 订单编号
     * @return bool
     */
    public function payUnlockData(int $id, int $unlockType, string $orderNum = '')
    {
        try
        {
            $nowTime = time();
            $data = [
                'status' => 1,
                'unlock_type' => $unlockType,
                'order_num' => $orderNum,
                'start_time' => $nowTime,
                'update_time' => $nowTime,
            ];
            $res = $this->UpdateData($id, $data);
            if ($res)
            {   //  八字起名 队列添加
                Util::queuePush('horoscope_name_analyze', ['id' => $id]);
                return true;
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
        return false;
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {   // 获取未删除 的数据
            $where = ['id' => ['in', $ids]];
        } else
        {   // 获取指定pid  未删除 且 未隐藏的数据
            $where = ['uid' => $type[0]];
        }
        $field = 'uid,status,rid,surname,name,unlock_type,order_num,back_rid,wx_analysis,content,share_help_info,start_time,success_time,create_time,update_time';
        try
        {
            $data = $this->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'rid', 'status', 'unlock_type', 'back_rid', 'create_time', 'update_time', 'start_time', 'success_time']);

            if (isset($itemData['content']))
            {
                $data[$index]['content'] = $itemData['content'] ? json_decode($itemData['content'], true) : [];
            }
            if (isset($itemData['share_help_info']))
            {
                $data[$index]['share_help_info'] = $itemData['share_help_info'] ? json_decode($itemData['share_help_info'], true) : [];
            }
        }

        return $data;
    }

    /**
     * @param int $uid
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function pageDataIds(int $uid, int $page, int $limit)
    {
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid])->order("id {$sortType}")->column('id');
                    $resData = [];
                    foreach ($data as $id)
                    {
                        $resData[$id] = ['id' => $id];
                    }
                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0);
        if ($resData['data'])
        {
            $resData['data'] = array_map('intval', array_keys($resData['data']));
        }
        return $resData;
    }

    public function getPageListData(int $uid, int $page, int $pageSize = 15)
    {
        $pageData = $this->pageDataIds($uid, $page, $pageSize);

        $data = $pageData['data'] ? $this->batchGetInfoByIds($pageData['data']) : [];
        $nowTime = time();
        $dataList = [];
        foreach ($pageData['data'] as $id)
        {
            if (!isset($data[$id]))
            {
                continue;
            }
            $dataItem = $data[$id];
            $list = ['档案：' . $dataItem['content']['birth_time']];
            switch ($dataItem['unlock_type'])
            {
                case 1:
                    $list[] = '支付类型：邀请好友解锁';
                    break;
                case 2:
                    $list[] = '支付类型：微信支付';
                    break;
                case 3:
                    $list[] = '支付类型：支付宝支付';
                    break;
                case 4:
                    $list[] = '支付类型：准币';
                    break;
                default:
                    $list[] = '支付类型：暂未解锁';
            }
            switch ($dataItem['status'])
            {
                case 1:
                case 3:
                    $scoreDesc = '计算中';
                    if ($nowTime - $dataItem['start_time'] > 300)
                    {   // 计算中 或 计算失败
                        $this->UpdateData($id, ['status' => 1, 'start_time' => $nowTime, 'update_time' => $nowTime]);
                        Util::queuePush('horoscope_name_analyze', ['id' => $id]);
                    }
                    break;
                case 2:
                    $scoreDesc = $dataItem['content']['score'] . '分';
                    break;
                default:
                    $scoreDesc = '暂无评分';
            }
            $dataList[] = [
                'id' => $dataItem['id'],
                'create_time' => date('Y.m.d H:i', $dataItem['create_time']),
                'title' => sprintf('%s%s', $dataItem['surname'], $dataItem['name']),
                'score_desc' => $scoreDesc,
                'type' => 1,
                'list' => $list,
                'right_desc' => '评分',
            ];
        }
        $pageData['data'] = $dataList;

        return $pageData;
    }

    /**
     * 数据重组
     * @param array $data
     * @return array
     */
    public function dataResert(array $data)
    {
        // $data['content'] = [
        //     'names' => $nameDatas,
        //     'birth_time' => sprintf('%d年%02d月%02d日 %02d:%02d', $recodeInfo['year'], $recodeInfo['month'], $recodeInfo['day'], $recodeInfo['hour'], $recodeInfo['minute']),
        //     'score' => '', // 分数
        //     'percentage' => '',  //  百分比
        //     'wx_score' => '',    //  五行分数
        //     'wx_analysis' => '', //  五行分析
        //     'ys_score' => '',    //  喜用神分数
        //     'ys_analysis' => '', //  喜用神分析
        //     'qh_score' => '',    //  整体契合分数
        //     'qh_analysis' => '', //  整体契合分析
        // ];
        $dataList = [
            [
                'score' => -1,
                'desc' => '',
                'title' => '五行',
                'icon' => '/test/name_analyze/wx_icon.png',
                'color' => '#FA7878',
                'type' => 3,
            ], [
                'score' => -1,
                'desc' => '/test/name_analyze/unlock_img.png',
                'title' => '喜用神',
                'icon' => '/test/name_analyze/ys_icon.png',
                'color' => '#6CB6FF',
                'type' => 2,
            ], [
                'score' => -1,
                'desc' => '/test/name_analyze/unlock_img.png',
                'title' => '整体契合',
                'icon' => '/test/name_analyze/qh_icon.png',
                'color' => '#EA944B',
                'type' => 2,
            ],
        ];
        if ($data['status'] === 2)
        {   // 计算成功
            $score = $data['content']['score'];
            $hintMiddle = $data['content']['percentage'];
            $helpUsers = [];
            $dataList[0]['score'] = $data['content']['wx_score'];
            $dataList[1]['score'] = $data['content']['ys_score'];
            $dataList[2]['score'] = $data['content']['qh_score'];
            $dataList[0]['type'] = 1;
            $dataList[1]['type'] = 1;
            $dataList[2]['type'] = 1;
            $dataList[0]['desc'] = $data['wx_analysis'];
            $dataList[1]['desc'] = $data['content']['ys_analysis'];
            $dataList[2]['desc'] = $data['content']['qh_analysis'];

            $btnData = ['name' => '帮TA选个新名字', 'target' => 'local', 'link' => 'horoscope_name_index?tab_index=1&need_auth=0',];
        } else
        {   // 未解锁 ｜ 计算中
            $score = '？';
            $hintMiddle = '？';
            $helpUsers = [];
            foreach ($data['share_help_info'] as $datum)
            {
                $helpUsers[] = [
                    'avatar' => $datum['avatar'],
                    'name' => $datum['name'],
                ];
            }
            if (isset($data['wx_analysis']) && $data['wx_analysis'])
            {
                $dataList[0]['desc'] = $data['wx_analysis'];
                $dataList[0]['type'] = 1;
            }
            if (!$data['status'])
            {
                $btnData = ['name' => '9.9元全部解锁', 'target' => 'local', 'link' => 'pay_order?type=35&gid=164&need_auth=2',];
            } else
            {
                $btnData = ['name' => '计算中(预计1分钟完成)…', 'target' => 'local', 'link' => 'empty',];
            }
        }
        $host = Env::get('host.domain');

        $resData = [
            'names' => $data['content']['names'],
            'score' => (string)$score,
            'status' => $data['status'],
            'data_list' => $dataList,
            'help_users' => $helpUsers,
            'btn_data' => $btnData,
            'share_url' => $host . '/web/horoscope_demo/nameanalyze',
            'help_toast' => '',
            'id' => $data['id'],
            'help_user_hint' => $data['status'] !== 2 ? '邀请3位好友成功解锁，预计10分钟内完成' : '',
            'hint_pre' => '经过AI分析：分值低于',
            'hint_middle' => (string)$hintMiddle,
            'hint_last' => '的小伙伴',
        ];

        return $resData;
    }
}
